package com.javacoo.swing.jxbrowser.content;

import java.awt.BorderLayout;

import javax.swing.JFrame;
import javax.swing.WindowConstants;

import com.javacoo.swing.jxbrowser.BaseBrowser;
import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.NetworkService;
import com.teamdev.jxbrowser.chromium.ResourceHandler;
import com.teamdev.jxbrowser.chromium.ResourceParams;
import com.teamdev.jxbrowser.chromium.ResourceType;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;

/**
 * 处理资源加载
 * <li></li>
 * 使用ResourceHandler，您可以确定是否应加载HTML，图像，JavaScript和CSS文件，favicon等资源。默认情况下，将加载所有资源。要修改默认行为，您需要注册自己的ResourceHandler实现。例如：
 *
 * NetworkService networkService = browser.getContext().getNetworkService();
 * networkService.setResourceHandler(new ResourceHandler() {
 *     @Override
 *     public boolean canLoadResource(ResourceParams params) {
 *         boolean isNotAnImageType =
 *                 params.getResourceType() != ResourceType.IMAGE;
 *         if (isNotAnImageType) {
 *             return true;
 *         }
 *
 *         // Cancel loading of all images
 *         return false;
 *     }
 * });
 *
 * 此实现取消了所有图像的加载。使用相同的技术，您可以实现并注册自己的 ResourceHandler ，您可以在其中取消所需资源的加载
 * @author: duanyong@jccfc.com
 * @since: 2020/9/25 10:08
 */
public class HandlingResourcesLoading extends BaseBrowser {
    public static void main(String[] args) {
        Browser browser = new Browser();
        BrowserView browserView = new BrowserView(browser);

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browserView, BorderLayout.CENTER);
        frame.setSize(700, 500);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        NetworkService networkService = browser.getContext().getNetworkService();
        networkService.setResourceHandler(new ResourceHandler() {
            @Override
            public boolean canLoadResource(ResourceParams params) {
                System.out.println("URL: " + params.getURL());
                System.out.println("Type: " + params.getResourceType());
                boolean isNotImageType =
                    params.getResourceType() != ResourceType.IMAGE;
                if (isNotImageType) {
                    return true;    // Cancel loading of all images
                }
                return false;
            }
        });

        browser.loadURL(BASE_URL);
    }
}
